import React, { useEffect, useState } from 'react'
import { Routes, Route, Navigate } from 'react-router-dom'
import Library from './pages/Library'
import Import from './pages/Import'
import PhotoDetail from './pages/PhotoDetail'
import Settings from './pages/Settings'
import './App.css'

/**
 * 应用主组件
 * 负责路由配置和全局状态管理
 */
function App() {
  const [isLoading, setIsLoading] = useState(true)
  const [appInfo, setAppInfo] = useState<{
    name: string
    version: string
  } | null>(null)

  /**
   * 初始化应用
   */
  useEffect(() => {
    const initializeApp = async () => {
      try {
          // 检查 photosAPI 是否可用
          if (typeof window !== 'undefined' && window.photosAPI) {
            // 获取应用信息
            const appInfo = await window.photosAPI.getAppInfo();
            setAppInfo(appInfo);
            
            console.log(`${appInfo.name} v${appInfo.version} 已启动`)
          } else {
            console.warn('photosAPI 不可用，可能在开发环境中')
          }
        } catch (error) {
        console.error('应用初始化失败:', error)
      } finally {
        setIsLoading(false)
      }
    }

    initializeApp()
  }, [])

  // 监听来自主进程的消息
  useEffect(() => {
    if (typeof window !== 'undefined' && window.photosAPI) {
      // 监听导航到设置页面的消息
      window.photosAPI.on('navigate-to-settings', () => {
        window.location.hash = '#/settings'
      })

      // 监听导入文件夹的消息
      window.photosAPI.on('import-folders', (folderPaths: string[]) => {
        console.log('收到导入文件夹请求:', folderPaths)
        // 导航到导入页面并传递文件夹路径
        window.location.hash = `#/import?folders=${encodeURIComponent(JSON.stringify(folderPaths))}`
      })

      // 清理函数
      return () => {
        window.photosAPI.off('navigate-to-settings', () => {})
        window.photosAPI.off('import-folders', () => {})
      }
    }
  }, [])

  if (isLoading) {
    return (
      <div className="app-loading">
        <div className="loading-spinner"></div>
        <p>正在初始化应用...</p>
      </div>
    )
  }

  return (
    <div className="app">
      <Routes>
        {/* 默认重定向到图库页面 */}
        <Route path="/" element={<Navigate to="/library" replace />} />
        
        {/* 图库页面 */}
        <Route path="/library" element={<Library />} />
        
        {/* 导入页面 */}
        <Route path="/import" element={<Import />} />
        
        {/* 照片详情页面 */}
        <Route path="/photo/:id" element={<PhotoDetail />} />
        
        {/* 设置页面 */}
        <Route path="/settings" element={<Settings />} />
        
        {/* 404 页面 */}
        <Route path="*" element={<Navigate to="/library" replace />} />
      </Routes>
      
      {/* 应用信息（开发环境显示） */}
      {process.env.NODE_ENV === 'development' && appInfo && (
        <div className="app-info">
          {appInfo.name} v{appInfo.version}
        </div>
      )}
    </div>
  )
}

export default App